package com.qyer.lxp.common.framework.convert;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by jiangping on 16/5/10.
 */
public final class JAXBCache {

    private final ConcurrentMap<String, JAXBContext> contextCache = new ConcurrentHashMap<String, JAXBContext>();

    private JAXBCache() {
    }

    private static class JAXBCacheHolder{
        private static final JAXBCache instance = new JAXBCache();
    }

    public static final JAXBCache instance() {
        return JAXBCacheHolder.instance;
    }

    JAXBContext getJAXBContext(Class<?> clazz) throws JAXBException {
        JAXBContext context = contextCache.get(clazz.getName());
        if (context == null) {
            context = JAXBContext.newInstance(clazz);
            contextCache.putIfAbsent(clazz.getName(), context);
        }
        return context;
    }
}
